package leets.leet2359;

import Main.Main;

import java.util.HashSet;
import java.util.Set;

public class Solution {
    public int closestMeetingNode(int[] edges, int node1, int node2) {
        int temp1=node1,temp2=node2;
        Set<Integer> set1=new HashSet<>();
        Set<Integer> set2=new HashSet<>();
        while (true){
            if(set2.contains(temp1)&&set1.contains(temp2)){
                return Math.min(temp1,temp2);
            }
            if(set1.contains(temp2)){
                return temp2;
            }
            if (set2.contains(temp1)){
                return temp1;
            }


            if(temp1==temp2){
                return temp1;
            }
            if((edges[temp1]==-1||set1.contains(temp1))&&(edges[temp2]==-1||set2.contains(temp2))){
                return -1;
            }

            set1.add(temp1);
            set2.add(temp2);

            temp1=edges[temp1]==-1?temp1:edges[temp1];
            temp2=edges[temp2]==-1?temp2:edges[temp2];

        }
    }
}